<template>
  <view class="ai-service-page">
    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y 
      :scroll-top="scrollTop" 
      scroll-with-animation
    >
      <view v-for="(message, index) in messages" :key="index" class="message-item">
        <!-- 用户消息 -->
        <view v-if="message.type === 'user'" class="user-message-wrapper">
          <view class="user-message">
            <text class="message-text">{{ message.content }}</text>
            <text class="message-time">{{ message.time }}</text>
          </view>
          <image class="avatar user-avatar" src="/static/user-avatar.svg" mode="aspectFill"></image>
        </view>
        
        <!-- AI消息 -->
        <view v-else class="ai-message-wrapper">
          <image class="avatar ai-avatar" src="/static/ai-avatar.svg" mode="aspectFill"></image>
          <view class="ai-message">
            <view class="ai-header">
              <text class="ai-name">AI客服小助手</text>
              <text v-if="message.isTyping" class="typing-indicator">正在输入...</text>
            </view>
            <text class="message-text">{{ message.content }}</text>
            <text class="message-time">{{ message.time }}</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="messages.length === 0" class="empty-state">
        <image class="empty-icon" src="/static/ai-welcome.svg" mode="aspectFit"></image>
        <text class="empty-title">AI客服小助手</text>
        <text class="empty-desc">您好！我是您的专属购物助手，有什么可以帮助您的吗？</text>
        
        <!-- 快捷问题 -->
        <view class="quick-questions">
          <view 
            v-for="(question, index) in quickQuestions" 
            :key="index" 
            class="quick-question-item"
            @tap="sendQuickQuestion(question)"
          >
            <text class="quick-question-text">{{ question }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 -->
    <view class="input-area">
      <!-- 连接状态提示 -->
      <view v-if="connectionStatus !== 'idle'" class="connection-status">
        <text class="status-text" :class="connectionStatus">
          {{ getConnectionStatusText() }}
        </text>
        <view v-if="connectionStatus === 'connecting'" class="loading-dots">
          <text class="dot">●</text>
          <text class="dot">●</text>
          <text class="dot">●</text>
        </view>
      </view>
      
      <view class="input-wrapper">
        <input 
          class="message-input" 
          v-model="inputMessage" 
          placeholder="请输入您的问题..."
          :disabled="isLoading"
          @confirm="sendMessage"
          @focus="onInputFocus"
          confirm-type="send"
          :adjust-position="false"
        />
        
        <!-- 发送/取消按钮 -->
        <button 
          v-if="!isLoading"
          class="send-button" 
          :class="{ 'disabled': !inputMessage.trim() }"
          @tap="sendMessage"
          :disabled="!inputMessage.trim()"
        >
          <text class="send-icon">📤</text>
        </button>
        
        <button 
          v-else
          class="cancel-button"
          @tap="cancelSend"
        >
          <text class="cancel-icon">✖️</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import ChatAPI from '@/utils/chatAPI.js';

export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      scrollTop: 0,
      quickQuestions: [
        '这款商品有什么颜色？',
        '什么时候能发货？',
        '支持退换货吗？',
        '有什么优惠活动？'
      ],
      chatAPI: null,
      currentTaskId: null,
      isConnecting: false,
      connectionStatus: 'idle' // idle, connecting, connected, error
    }
  },
  
  onLoad() {
    // 初始化ChatAPI
    this.initChatAPI()
    
    // 页面加载时显示欢迎消息
    this.showWelcomeMessage()
    
    // 监听键盘弹起和收起
    uni.onKeyboardHeightChange((res) => {
      if (res.height > 0) {
        // 键盘弹起时，滚动到底部
        this.scrollToBottom()
      }
    })
  },
  
  onUnload() {
    // 页面卸载时清理资源
    if (this.chatAPI) {
      this.chatAPI.destroy()
    }
  },
  
  methods: {
    /**
     * 初始化ChatAPI
     */
    initChatAPI() {
      this.chatAPI = new ChatAPI({
        onMessage: this.handleStreamMessage,
        onError: this.handleStreamError,
        onComplete: this.handleStreamComplete,
        onConnectionChange: this.handleConnectionChange
      })
    },
    
    /**
     * 显示欢迎消息
     */
    showWelcomeMessage() {
      // 延迟显示，增加真实感
      setTimeout(() => {
        this.addAIMessage('您好！欢迎来到我们的商城，我是AI客服小助手。有什么可以帮助您的吗？')
      }, 500)
    },
    
    /**
     * 发送消息
     */
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const userMessage = this.inputMessage.trim()
      this.inputMessage = ''
      
      // 添加用户消息
      this.addUserMessage(userMessage)
      
      // 发送到AI服务
      await this.sendToAI(userMessage)
    },
    
    /**
     * 发送快捷问题
     */
    async sendQuickQuestion(question) {
      if (this.isLoading) return
      
      this.addUserMessage(question)
      await this.sendToAI(question)
    },
    
    /**
     * 添加用户消息
     */
    addUserMessage(content) {
      this.messages.push({
        type: 'user',
        content: content,
        time: this.getCurrentTime()
      })
      this.scrollToBottom()
    },
    
    /**
     * 添加AI消息
     */
    addAIMessage(content, isTyping = false) {
      this.messages.push({
        type: 'ai',
        content: content,
        time: this.getCurrentTime(),
        isTyping: isTyping
      })
      this.scrollToBottom()
    },
    
    /**
     * 发送到AI服务
     */
    async sendToAI(message) {
      this.isLoading = true
      this.connectionStatus = 'connecting'
      
      // 添加AI消息占位符
      const aiMessageIndex = this.messages.length
      this.addAIMessage('', true)
      
      try {
        // 使用ChatAPI发送消息
        await this.chatAPI.sendMessage(message, {
          messageIndex: aiMessageIndex
        })
        
      } catch (error) {
        console.error('AI聊天失败:', error)
        this.updateAIMessage(aiMessageIndex, '抱歉，服务暂时不可用，请稍后重试。', false)
        
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
        
        this.connectionStatus = 'error'
      } finally {
        this.isLoading = false
      }
    },
    
    /**
     * 处理流式消息
     */
    handleStreamMessage(data) {
      const { messageIndex } = data.context || {}
      if (messageIndex !== undefined) {
        this.updateAIMessage(messageIndex, data.content, true)
      }
    },
    
    /**
     * 处理流式错误
     */
    handleStreamError(error) {
      console.error('流式聊天错误:', error)
      uni.showToast({
        title: error.message || '网络异常，请重试',
        icon: 'none'
      })
      this.connectionStatus = 'error'
    },
    
    /**
     * 处理流式完成
     */
    handleStreamComplete(data) {
      const { messageIndex } = data.context || {}
      if (messageIndex !== undefined) {
        this.updateAIMessage(messageIndex, data.content, false)
      }
      this.connectionStatus = 'connected'
      console.log(`AI回复完成，耗时: ${data.responseTime}ms, 来自缓存: ${data.fromCache}`)
    },
    
    /**
      * 处理连接状态变化
      */
     handleConnectionChange(status) {
       this.connectionStatus = status
       console.log('连接状态变化:', status)
     },
     
     /**
      * 获取连接状态文本
      */
     getConnectionStatusText() {
       switch (this.connectionStatus) {
         case 'connecting':
           return 'AI正在思考中'
         case 'connected':
           return 'AI回复完成'
         case 'error':
           return '连接异常，请重试'
         default:
           return ''
       }
     },
    
    /**
     * 取消当前发送
     */
    async cancelSend() {
      if (this.chatAPI && this.isLoading) {
        try {
          await this.chatAPI.cancelCurrentTask()
          this.isLoading = false
          this.connectionStatus = 'idle'
          
          // 移除最后一条AI消息（如果是占位符）
          const lastMessage = this.messages[this.messages.length - 1]
          if (lastMessage && lastMessage.type === 'ai' && !lastMessage.content.trim()) {
            this.messages.pop()
          }
          
          uni.showToast({
            title: '已取消发送',
            icon: 'success'
          })
        } catch (error) {
          console.error('取消发送失败:', error)
        }
      }
    },
    
    /**
     * 打字机效果（保留用于兼容性）
     */
    typewriterEffect(messageIndex, fullText) {
      let index = 0
      const timer = setInterval(() => {
        const currentText = fullText.substring(0, index + 1)
        this.updateAIMessage(messageIndex, currentText, index < fullText.length - 1)
        
        index++
        
        if (index >= fullText.length) {
          clearInterval(timer)
        }
      }, 50) // 每50ms显示一个字符
    },
    
    /**
     * 更新AI消息
     */
    updateAIMessage(messageIndex, content, isTyping) {
      if (this.messages[messageIndex]) {
        this.messages[messageIndex].content = content
        this.messages[messageIndex].isTyping = isTyping
        this.messages[messageIndex].time = this.getCurrentTime()
      }
    },
    
    /**
     * 获取当前时间
     */
    getCurrentTime() {
      const now = new Date()
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    },
    
    /**
     * 输入框聚焦处理
     */
    onInputFocus() {
      // 延迟滚动到底部，确保键盘完全弹起
      setTimeout(() => {
        this.scrollToBottom()
      }, 300)
    },
    
    /**
     * 滚动到底部
     */
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999
      })
    }
  }
}
</script>

<style scoped>
.ai-service-page {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  box-sizing: border-box;
  position: relative;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  padding-bottom: 140rpx;
  width: 100%;
  box-sizing: border-box;
  min-height: calc(100vh - 140rpx);
}

.message-item {
  margin-bottom: 30rpx;
  width: 100%;
  box-sizing: border-box;
}

/* 用户消息样式 */
.user-message-wrapper {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  width: 100%;
  box-sizing: border-box;
}

.user-message {
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  padding: 20rpx 24rpx;
  border-radius: 24rpx 24rpx 8rpx 24rpx;
  max-width: 60%;
  margin-right: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 123, 255, 0.3);
  word-wrap: break-word;
  word-break: break-all;
  box-sizing: border-box;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  border: 4rpx solid #ffffff;
  flex-shrink: 0;
}

/* AI消息样式 */
.ai-message-wrapper {
  display: flex;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
}

.ai-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 4rpx solid #e9ecef;
  flex-shrink: 0;
}

.ai-message {
  background: white;
  padding: 20rpx 24rpx;
  border-radius: 24rpx 24rpx 24rpx 8rpx;
  max-width: 60%;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
  word-break: break-all;
  box-sizing: border-box;
}

.ai-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
  flex-wrap: wrap;
}

.ai-name {
  font-size: 24rpx;
  color: #007bff;
  font-weight: bold;
  margin-right: 16rpx;
}

.typing-indicator {
  font-size: 22rpx;
  color: #28a745;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.message-text {
  font-size: 28rpx;
  line-height: 1.5;
  color: #333333;
  word-wrap: break-word;
  word-break: break-all;
  display: block;
  margin-bottom: 8rpx;
}

.user-message .message-text {
  color: white;
}

.message-time {
  font-size: 20rpx;
  color: #999999;
  display: block;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 40rpx;
  text-align: center;
  width: 100%;
  box-sizing: border-box;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 40rpx;
}

.empty-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.5;
  margin-bottom: 60rpx;
  padding: 0 20rpx;
}

.quick-questions {
  width: 100%;
  box-sizing: border-box;
}

.quick-question-item {
  background: white;
  padding: 24rpx 32rpx;
  margin-bottom: 20rpx;
  border-radius: 16rpx;
  border: 2rpx solid #e9ecef;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.quick-question-item:active {
  background: #f8f9fa;
  transform: scale(0.98);
}

.quick-question-text {
  font-size: 26rpx;
  color: #007bff;
  text-align: center;
  display: block;
  word-wrap: break-word;
}

/* 输入区域样式 */
.input-area {
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #e9ecef;
  width: 100%;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
  /* 适配安全区域 */
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

/* 连接状态提示 */
.connection-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
  margin-bottom: 10rpx;
}

.status-text {
  font-size: 24rpx;
  margin-right: 10rpx;
}

.status-text.connecting {
  color: #007aff;
}

.status-text.connected {
  color: #34c759;
}

.status-text.error {
  color: #ff3b30;
}

/* 加载动画点 */
.loading-dots {
  display: flex;
  align-items: center;
}

.dot {
  font-size: 20rpx;
  color: #007aff;
  margin: 0 2rpx;
  animation: loading-dot 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading-dot {
  0%, 80%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 取消按钮样式 */
.cancel-button {
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #ff3b30, #d70015);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(255, 59, 48, 0.3);
  flex-shrink: 0;
}

.cancel-button:active {
  transform: scale(0.95);
}

.cancel-icon {
  font-size: 28rpx;
  line-height: 1;
  color: white;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 50rpx;
  padding: 8rpx;
  width: 100%;
  box-sizing: border-box;
}

.message-input {
  flex: 1;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  border: none;
  background: transparent;
  outline: none;
  min-width: 0;
  box-sizing: border-box;
}

.send-button {
  width: 80rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #007bff, #0056b3);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(0, 123, 255, 0.3);
  flex-shrink: 0;
}

.send-button.disabled {
  background: #dee2e6;
  box-shadow: none;
}

.send-button:active:not(.disabled) {
  transform: scale(0.95);
}

.send-icon {
  font-size: 32rpx;
  line-height: 1;
}

.send-icon.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 移动端适配 */
@media screen and (max-width: 750rpx) {
  .user-message,
  .ai-message {
    max-width: 70%;
  }
  
  .empty-icon {
    width: 120rpx;
    height: 120rpx;
  }
  
  .empty-title {
    font-size: 28rpx;
  }
  
  .empty-desc {
    font-size: 24rpx;
  }
}
</style>